using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.DirectX;
using Microsoft.DirectX.Direct3D;

namespace IngenEngine
{
	public class MeshInformation
	{
		Material[] materials;
		Texture[] textures;
		Mesh mesh;

		#region Properties
		public MeshInformation(Material[] materials,
			Texture[] textures, Mesh mesh)
		{
			this.materials = materials;
			this.textures = textures;
			this.mesh = mesh;
		}

		public Material[] MeshMaterials
		{
			get { return this.materials; }
			set { this.materials = value; }
		}

		public Texture[] MeshTextures
		{
			get { return this.textures; }
			set { this.textures = value; }
		}

		public Mesh PrimaryMesh
		{
			get { return this.mesh; }
			set { this.mesh = value; }
		}  
		#endregion
	}
	
	public class MeshHelper
	{
		/// <summary>
		/// Loads a mesh
		/// </summary>
		/// <param name="dir">Directory of mesh resources</param>
		/// <param name="file">the .x file</param>
		public static MeshInformation LoadMesh(ref Device device, string dir, string file)
		{
			MeshInformation information;
			Mesh mesh = null;
			Material[] meshMaterials = null;
			Texture[] meshTextures = null;
			ExtendedMaterial[] mtrl = null;

			mesh =
				Mesh.FromFile(dir + file,		//File to get from
							MeshFlags.Managed,	//MeshFlags
							device,				//Device to bind to
							out mtrl);			//Materials data

			//if we have any materials, store them
			if ((mtrl != null) && (mtrl.Length > 0))
			{
				meshMaterials = new Material[mtrl.Length];
				meshTextures = new Texture[mtrl.Length];

				//Store each material and texture
				for (int i = 0; i < mtrl.Length; i++)
				{
					meshMaterials[i] = mtrl[i].Material3D;
					if (((mtrl)[i].TextureFilename != null)
						&& (mtrl[i].TextureFilename != string.Empty))
					{
						//We have a texture, try to load it
						meshTextures[i] =
							TextureLoader.FromFile(device, dir +
							mtrl[i].TextureFilename);
					}
				}
			}

			information = new MeshInformation(meshMaterials, meshTextures, mesh);
			return information;
		}

		public static void DrawMeshHelper(ref Device device, MeshInformation info, float yaw, float pitch, float roll, float x, float y, float z)
		{

			device.Transform.World = Matrix.RotationYawPitchRoll(yaw, pitch, roll) *
				Matrix.Translation(x, y, z);

			for (int i = 0; i < info.MeshMaterials.Length; i++)
			{
				device.Material = info.MeshMaterials[i];	//Load materials
				device.SetTexture(0, info.MeshTextures[i]);	//Load textures
				info.PrimaryMesh.DrawSubset(i);				//Draw!
			}
		}
	}
}